﻿using HZY.Quartz.Common;
using HZY.Quartz.Entitys;
using HZY.Quartz.Service;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace HZY.Quartz
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private readonly ITaskService _taskService;

        public Worker(ILogger<Worker> logger, ITaskService taskService)
        {
            _logger = logger;
            _taskService = taskService;
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation($"程序服务开始 : {DateTime.Now}");

            #region 对任务数据 状态 重置
            var result = (await _taskService.FindListAsync())?.ToList() ?? new List<Tasks>();

            foreach (var item in result.Where(w => w.State == StateEnum.运行中))
            {
                item.State = StateEnum.未运行;
                item.ExecuteTime = null;
                await _taskService.SaveAsync(item);
                //自动恢复任务机制
                try
                {
                    await _taskService.RunByIdAsync(item.Id.Value);
                }
                catch (Exception ex)
                {
                    if (ex is not MessageBox)
                    {
                        _logger.LogError(ex, $"自动开启任务错误 [{DateTime.Now}] : {ex.Message}");
                    }

                }
            }

            #endregion

            await base.StartAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //while (!stoppingToken.IsCancellationRequested)
            //{
            //    _logger.LogInformation("服务运行中 : {time}", DateTimeOffset.Now);
            //    await Task.Delay(1000, stoppingToken);
            //}
            await Task.CompletedTask;
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogError($"程序服务结束 : {DateTime.Now}");

            await base.StopAsync(cancellationToken);
        }

        public override void Dispose()
        {
            _logger.LogInformation($"程序服务 Dispose 释放 : {DateTime.Now}");

            base.Dispose();
        }



    }
}
